﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace 序列化和反序列化
{

	//序列化：对象转换为二进制
	//反序列化：二进制转换为对象
	//作业：
	//只有被[Serializable]标记 ，类才可以序列化
	class Program
	{
		static void Main(string[] args)
		{
			Person p = new Person("张山",12);
			Person p2;
			//序列化
			using (FileStream fs = new FileStream(@"E:\file\存档.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
			{
				BinaryFormatter bf = new BinaryFormatter();
				bf.Serialize(fs,p);
			}
			Console.WriteLine("序列化成功");
		
			//反序列化
			using(FileStream fs =new FileStream(@"E:\file\存档.txt", FileMode.OpenOrCreate, FileAccess.Read))
			{
				BinaryFormatter bf = new BinaryFormatter();
				p2=(Person)bf.Deserialize(fs);
			}
			Console.WriteLine("反序列化成功\n"+p2.Age+p2.Name);

			Console.ReadKey();
		}
		
	}
	[Serializable]
	public class Person
	{
		public Person(string name,int age)
		{
			Name = name;
			Age = age;
		}
		private string _name;
		private int _age;
		public string Name { get => _name; set => _name = value; }
		public int Age { get => _age; set => _age = value; }
	}
}
